"use client";

import { Breadcrumb } from "@/components/ui/breadcrumb";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { FileItemComponent } from "@/components/ui/file-item";
import { Input } from "@/components/ui/input";
import { MoveDialog } from "@/components/ui/move-dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { UploadArea } from "@/components/ui/upload-area";
import { FileItem, useCreateDirectory, useDeleteFile, useFiles, useMoveFile } from "@/hooks/useFiles";
import { Folder, FolderPlus, Search } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";

export default function ExplorePage() {
    const [currentPath, setCurrentPath] = useState("");
    const [searchTerm, setSearchTerm] = useState("");
    const [sortBy, setSortBy] = useState<"name" | "type" | "size" | "modifiedTime">("name");
    const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
    const [newFolderName, setNewFolderName] = useState("");
    const [open, setOpen] = useState(false);
    const [moveDialogOpen, setMoveDialogOpen] = useState(false);
    const [selectedItem, setSelectedItem] = useState<FileItem | null>(null);

    const {
        data: filesData,
        isLoading,
        error,
    } = useFiles({
        path: currentPath,
        search: searchTerm,
        sortBy,
        sortOrder,
    });

    const deleteMutation = useDeleteFile();
    const createDirectoryMutation = useCreateDirectory();
    const moveMutation = useMoveFile();

    const handleNavigate = (path: string) => {
        setCurrentPath(path);
    };

    const handleCopyLink = (path: string) => {
        const url = `${window.location.origin}/view?model=${encodeURIComponent(path)}`;
        navigator.clipboard.writeText(url).then(() => {
            toast.success("链接已复制到剪贴板");
        });
    };

    if (error) {
        return (
            <div className="flex items-center justify-center h-96">
                <p className="text-destructive">加载失败: {error.message}</p>
            </div>
        );
    }

    return (
        <div className="flex h-screen bg-background">
            {/* 右侧文件列表 */}
            <div className="flex-1 flex flex-col">
                {/* 顶部工具栏 */}
                <div className="border-b border-border p-4 space-y-4">
                    <div className="flex items-center justify-between">
                        <Breadcrumb path={currentPath} onNavigate={handleNavigate} />
                    </div>

                    <div className="flex items-center space-x-4">
                        <div className="flex-1 relative">
                            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                            <Input placeholder="搜索文件..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="pl-10" />
                        </div>

                        {/* <select value={sortBy} onChange={(e) => setSortBy(e.target.value as any)} className="px-3 py-2 border border-input rounded-md bg-background">
                            <option value="name">按名称</option>
                            <option value="type">按类型</option>
                            <option value="size">按大小</option>
                            <option value="modifiedTime">按修改时间</option>
                        </select> */}

                        <Select value={sortBy} onValueChange={(value) => setSortBy(value as "name" | "type" | "size" | "modifiedTime")}>
                            <SelectTrigger>
                                <SelectValue placeholder="选择排序方式" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="name">按名称</SelectItem>
                                <SelectItem value="type">按类型</SelectItem>
                                <SelectItem value="size">按大小</SelectItem>
                                <SelectItem value="modifiedTime">按修改时间</SelectItem>
                            </SelectContent>
                        </Select>

                        <Button variant="outline" size="sm" onClick={() => setSortOrder(sortOrder === "asc" ? "desc" : "asc")}>
                            {sortOrder === "asc" ? "↑" : "↓"}
                        </Button>
                    </div>
                </div>

                {/* 文件列表 */}
                <div className="flex-1 overflow-auto p-4">
                    {isLoading ? (
                        <div className="flex items-center justify-center h-64">
                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                        </div>
                    ) : filesData?.data?.length === 0 ? (
                        <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
                            <Folder className="h-12 w-12 mb-4" />
                            <p>当前目录为空</p>
                        </div>
                    ) : (
                        <div className="space-y-2">
                            {filesData?.data?.map((item: FileItem) => (
                                <FileItemComponent key={item.path} item={item} onNavigate={handleNavigate} onCopyLink={handleCopyLink} />
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
